package com.example.demo.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.example.demo.pojo.User;
import com.example.demo.service.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService userService;


	/**
	 * 查询所有
	 */
	@GetMapping("/users")
	public String findAll(Model model) {
		List<User> users = userService.findAll();
		model.addAttribute("users", users);
		return "emp/user";
	}

	@GetMapping("/deleteUserById/{id}")
	public String deleteUserById(@PathVariable("id") long id) {
		userService.deleteById(id);
		return "redirect:/users";
	}

	// 查询
	@GetMapping("/user")
	public String toAddPage(Model model) {
		return "emp/useradd";
	}

	// 提交表单
	@PostMapping("/user")
	public String addPage(User user) {
		// 调试
		// System.out.println(user);
		userService.save(user);
		System.out.println(user);
		return "redirect:/users";
	}

	// 跳转员工修改的页面
	@GetMapping("/user/{id}")
	public String toUpdatePage(@PathVariable("id") long id, Model model) {
		User user = userService.findUserById(id);
		model.addAttribute("user", user);
		return "emp/userupdate";
	}

	// 保存修改的页面
	@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
	public String updateEmp(User user) {
		userService.save(user);
		return "redirect:/users";
	}

}
